const { apps: mock } = require('../mock/apps')
const { get } = require('../utils/http')
const { getUseMock } = require('../utils/env')

function normalize(app) {
  return Object.assign({}, app, {
    price: Number(app.price || 0),
    rating: Number(app.rating || 0),
    downloads: Number(app.downloads || 0),
    reviews: Number(app.reviews || 0)
  })
}

async function getApps() {
  if (getUseMock()) return mock.map(normalize)
  const list = await get('/api/apps')
  return (Array.isArray(list) ? list : []).map(normalize)
}

async function getAppsSortedByRating() {
  const { getUseMock } = require('../utils/env')
  if (getUseMock()) return mock.map(normalize).sort((a, b) => b.rating - a.rating)
  const { get } = require('../utils/http')
  const list = await get('/api/apps/sort/rating')
  return (Array.isArray(list) ? list : []).map(normalize)
}

async function getAppsSortedByDownloads() {
  const { getUseMock } = require('../utils/env')
  if (getUseMock()) return mock.map(normalize).sort((a, b) => b.downloads - a.downloads)
  const { get } = require('../utils/http')
  const list = await get('/api/apps/sort/downloads')
  return (Array.isArray(list) ? list : []).map(normalize)
}

async function getAppsByCategory(category) {
  const { getUseMock } = require('../utils/env')
  if (getUseMock()) return mock.filter(app => app.category === category).map(normalize)
  const { get } = require('../utils/http')
  const list = await get(`/api/apps/category/${category}`)
  return (Array.isArray(list) ? list : []).map(normalize)
}

async function getAppsByRating(rating) {
  const { getUseMock } = require('../utils/env')
  if (getUseMock()) return mock.filter(app => app.rating === rating).map(normalize)
  const { get } = require('../utils/http')
  const list = await get(`/apps/rating/${rating}`)
  return (Array.isArray(list) ? list : []).map(normalize)
}

async function getAppsByDownloads(downloads) {
  const { getUseMock } = require('../utils/env')
  if (getUseMock()) return mock.filter(app => app.downloads === downloads).map(normalize)
  const { get } = require('../utils/http')
  const list = await get(`/apps/downloads/${downloads}`)
  return (Array.isArray(list) ? list : []).map(normalize)
}

module.exports = { getApps, getAppsSortedByRating, getAppsSortedByDownloads }
